package com.zhaoyue.study.io.nio.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 2017/1/3
 * Time: 17:32
 * To change this template use File | Settings | File Templates.
 */
public class TimeClientHandle implements Runnable {

    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;

    public TimeClientHandle(String host,int port){
        try{
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            this.host = host;
            this.port = port;

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        try{
            doConnect();
        }catch (Exception e){
            e.printStackTrace();
        }

        try{
            while (!stop){
                selector.select(1000);//
                Set<SelectionKey> selectionKeySet = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeySet.iterator();
                while (it.hasNext()){
                    SelectionKey key = it.next();
                    it.remove();
                    handleInput(key);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                selector.close();
                socketChannel.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }



    }


    public void doConnect() throws IOException{
        if(socketChannel.connect(new InetSocketAddress(host,port))){
            System.out.println("客户端已经连接");
            socketChannel.register(selector, SelectionKey.OP_READ);
            doWrite(socketChannel);
        }else {
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }

    public void doWrite(SocketChannel sc) throws IOException{
        byte[] bytes = "QUERY TIME ORDER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        sc.write(writeBuffer);
        if(!writeBuffer.hasRemaining()){
            System.out.println("send common success");
        }
    }


    public void handleInput(SelectionKey selectionKey) throws IOException{
        if(selectionKey.isValid()){
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            if(selectionKey.isConnectable()){
                if(socketChannel.finishConnect()){
                    socketChannel.register(selector,SelectionKey.OP_READ);
                    doWrite(socketChannel);
                }else {
                    System.exit(1);
                }
            }

            if(selectionKey.isReadable()){
                System.out.println("客户端读就绪");
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int byteNums = socketChannel.read(byteBuffer);
                System.out.println(byteNums);

                String body = null;
                if (byteNums > 0) {
                    byteBuffer.flip();
                    byte[] bytes = new byte[byteBuffer.remaining()];
                    byteBuffer.get(bytes);
                    body = new String(bytes,"UTF-8");
                    System.out.println(body);
                }else {
                    selectionKey.cancel();
                    socketChannel.close();
                }
            }

        }
    }


    public static void main(String[] args) {
        new Thread(new TimeClientHandle("127.0.0.1",8080),"Thread_client").start();
    }
}
